<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>快速删除测试 - Cursor Remote Control</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            text-align: center;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #fafafa;
        }
        .btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            background: #2980b9;
        }
        .btn-danger {
            background: #e74c3c;
        }
        .btn-danger:hover {
            background: #c0392b;
        }
        .status {
            padding: 10px;
            border-radius: 6px;
            margin: 10px 0;
        }
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .history-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 15px;
            margin: 10px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .command-text {
            font-family: monospace;
            background: #f8f9fa;
            padding: 5px 8px;
            border-radius: 4px;
            flex-grow: 1;
            margin-right: 10px;
        }
        .log {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            margin: 10px 0;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 快速删除功能测试</h1>
        
        <div class="test-section">
            <h3>步骤 1: 连接测试</h3>
            <button class="btn" onclick="testConnection()">测试连接</button>
            <div id="connection-status"></div>
        </div>

        <div class="test-section">
            <h3>步骤 2: 获取历史记录</h3>
            <button class="btn" onclick="loadHistory()">加载历史记录</button>
            <div id="history-container"></div>
        </div>

        <div class="test-section">
            <h3>步骤 3: 添加测试数据</h3>
            <button class="btn" onclick="addTestData()">添加测试命令</button>
            <div id="add-status"></div>
        </div>

        <div class="test-section">
            <h3>控制台输出</h3>
            <button class="btn" onclick="clearConsole()">清空日志</button>
            <div id="console-output" class="log"></div>
        </div>
    </div>

    <script src="env-config.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
    <script>
        let supabaseClient = null;
        const consoleDiv = document.getElementById('console-output');

        // 重写console方法以在页面显示
        const originalConsole = {
            log: console.log,
            error: console.error,
            warn: console.warn
        };

        function logToPage(message, type = 'log') {
            const timestamp = new Date().toLocaleTimeString();
            const logLine = `[${timestamp}] ${type.toUpperCase()}: ${message}\n`;
            consoleDiv.textContent += logLine;
            consoleDiv.scrollTop = consoleDiv.scrollHeight;
            
            // 也输出到真实控制台
            originalConsole[type](message);
        }

        console.log = (msg) => logToPage(msg, 'log');
        console.error = (msg) => logToPage(msg, 'error');
        console.warn = (msg) => logToPage(msg, 'warn');

        function clearConsole() {
            consoleDiv.textContent = '';
        }

        function showStatus(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            element.innerHTML = `<div class="status ${type}">${message}</div>`;
        }

        async function testConnection() {
            console.log('🔍 开始测试连接...');
            
            try {
                if (typeof window.SUPABASE_URL === 'undefined' || typeof window.SUPABASE_ANON_KEY === 'undefined') {
                    throw new Error('Supabase配置缺失');
                }
                
                supabaseClient = supabase.createClient(window.SUPABASE_URL, window.SUPABASE_ANON_KEY);
                console.log('✅ Supabase客户端初始化成功');
                
                // 测试数据库连接
                const { data, error } = await supabaseClient
                    .from('commands')
                    .select('count')
                    .limit(1);

                if (error) {
                    throw error;
                }

                console.log('✅ 数据库连接成功');
                showStatus('connection-status', '✅ 连接测试通过', 'success');
                
            } catch (error) {
                console.error('❌ 连接测试失败:', error.message);
                showStatus('connection-status', `❌ 连接失败: ${error.message}`, 'error');
            }
        }

        async function loadHistory() {
            if (!supabaseClient) {
                alert('请先测试连接');
                return;
            }

            console.log('📋 加载历史记录...');

            try {
                const { data, error } = await supabaseClient.rpc('get_command_history_with_ids', {
                    limit_count: 10,
                    search_text: ''
                });

                if (error) {
                    throw error;
                }

                console.log('✅ 历史记录加载成功:', data.length, '条');

                let html = `<h4>历史记录 (${data.length} 条)</h4>`;
                
                if (data.length === 0) {
                    html += '<p>暂无历史记录，可以先添加一些测试数据</p>';
                } else {
                    data.forEach((item) => {
                        html += `
                            <div class="history-item">
                                <div class="command-text">${item.command_text}</div>
                                <button class="btn btn-danger" onclick="testDelete('${item.id}', '${item.command_text.replace(/'/g, "\\'")}')">
                                    删除
                                </button>
                            </div>
                        `;
                    });
                }

                document.getElementById('history-container').innerHTML = html;

            } catch (error) {
                console.error('❌ 加载历史记录失败:', error.message);
                showStatus('history-container', `❌ 加载失败: ${error.message}`, 'error');
            }
        }

        async function addTestData() {
            if (!supabaseClient) {
                alert('请先测试连接');
                return;
            }

            const testCommand = `测试删除命令 ${new Date().toLocaleTimeString()}`;
            console.log('➕ 添加测试数据:', testCommand);

            try {
                const { data, error } = await supabaseClient
                    .from('commands')
                    .insert([
                        {
                            command_text: testCommand,
                            executed_at: new Date().toISOString()
                        }
                    ])
                    .select();

                if (error) {
                    throw error;
                }

                console.log('✅ 测试数据添加成功');
                showStatus('add-status', '✅ 测试数据添加成功', 'success');
                
                // 重新加载历史记录
                setTimeout(loadHistory, 500);

            } catch (error) {
                console.error('❌ 添加测试数据失败:', error.message);
                showStatus('add-status', `❌ 添加失败: ${error.message}`, 'error');
            }
        }

        async function testDelete(commandId, commandText) {
            if (!supabaseClient) {
                alert('请先测试连接');
                return;
            }

            if (!confirm(`确定要删除命令: ${commandText}?`)) {
                return;
            }

            console.log('🗑️ 开始删除测试:', { commandId, commandText });

            try {
                // 模拟删除函数的逻辑
                const { data, error } = await supabaseClient.rpc('delete_command_by_id', {
                    p_command_id: commandId
                });

                if (error) {
                    throw error;
                }

                console.log('✅ 删除成功:', data);
                
                if (data.success && data.deleted_count > 0) {
                    console.log(`✅ 成功删除 ${data.deleted_count} 条记录`);
                    // 重新加载历史记录
                    setTimeout(loadHistory, 500);
                } else {
                    console.warn('⚠️ 删除操作返回异常结果:', data);
                }

            } catch (error) {
                console.error('❌ 删除失败:', error.message);
                console.error('错误详情:', error);
            }
        }

        // 页面加载时自动初始化
        window.addEventListener('load', () => {
            console.log('🚀 快速删除测试页面已加载');
        });
    </script>
</body>
</html>
